﻿<%@ WebHandler Language="C#" Class="keyDataTable" %>

using System;
using System.Web;
using System.Data;
using System.Text;
using System.Data.SqlClient;

public class keyDataTable : AjaxHandlerBase
{

    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":
                strResponse = getKeyList(context);
                break;
            case "getkeyuseinfo":
                strResponse = getKeyUseInfoList(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
  
    private string getKeyList(HttpContext context)
    {
      
        try {
            
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "ReceiptionId,ReceiptionCode,HouseAddress,KeyCount,Status,GetKeyDay,AddPerson";
            string fieldtablelist = "ReceiptionId,ReceiptionCode,HouseAddress,KeyCount,CASE Status when '0'  then '正常' when '10' then '借出' end as Status ,GetKeyDay,AddPerson";
            string orderfield = "House_KeyReceiptionInfo.GetKeyDay desc";

            Guid city = (string.IsNullOrEmpty(context.Request["city"])) ? CurrentUserInfo.CityId : new Guid(context.Request["city"]);
            Guid company = (string.IsNullOrEmpty(context.Request["company"])) ? CurrentUserInfo.CompanyId : new Guid(context.Request["company"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["businessdistrict"])) ? Guid.Empty : new Guid(context.Request["businessdistrict"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departs"])) ? Guid.Empty : new Guid(context.Request["departs"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["employee"])) ? Guid.Empty : new Guid(context.Request["employee"]);
            
            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (employee != Guid.Empty)
                sb.AppendFormat(" AND (AddPersonId = '{0}') ", employee);
            else if (departs != Guid.Empty)
                sb.AppendFormat(" AND (DepartId = '{0}')", departs);
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (DepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
                sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", company);
            else if (city != Guid.Empty)
                sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", city);

            string strPermitCode0 = "house.view.all.open";//查看所有非隐藏房源权限
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            if (CurrentUserInfo.ContainsPermit(strPermitCode0))
            {
                sb1.Append(" (1=1) ");
            }
            else
            {
                sb1.Append("(EXISTS(");
                sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
                sb1.AppendFormat("WHERE (House_BaseInfo.OprDepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
                sb1.Append("AND ((House_BaseInfo.IsProtectHouse = 1 AND M.ViewPrivHouse =1) OR ");
                sb1.Append("(House_BaseInfo.IsProtectHouse = 0 AND M.ViewPubHouse =1))");
                sb1.Append("))");
            }
            
            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string strquery = context.Request.QueryString["strquery"];
            string keystatus = context.Request.QueryString["keystatus"];
            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,GetKeyDay,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,GetKeyDay,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(strquery))
            {
                sb1.Append("AND HouseAddress LIKE '%" + strquery + "%'");
            }
            if (!String.IsNullOrEmpty(keystatus))
            {
                sb1.Append(string.Format(" and Status= '{0}'", keystatus));
            }
            //判断权限范围结束////////////////////////////////////////////
            
            
            System.Data.DataSet dskeylist = null;
            dskeylist = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_KeyReceiptionInfo", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)dskeylist.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(dskeylist, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            dskeylist.Dispose();
            dskeylist = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
         }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }
    
    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    { 
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"38\">钥匙编号</th>");
            sb.Append("<th width=\"38\">钥匙数量</th>");
            sb.Append("<th width=\"35\" >状态</th>");
            sb.Append("<th width=\"35\" >添加人</th>");
            sb.Append("<th width=\"40\">取得时间</th>");
            sb.Append("<th width=\"150\">地址</th>");
            sb.Append("</tr></thead><tbody>");
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["ReceiptionId"].ToString());
                //钥匙编号
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ReceiptionCode", ""));
                 //状态
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "KeyCount", ""));
                //状态
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));
                //添加人
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "AddPerson", ""));
                //取得时间
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "GetKeyDay", ""));
                //地址
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""));
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }

    /// <summary>
    /// 根据参数中的房源ID查询房源跟单数据;
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private string getKeyUseInfoList(HttpContext context)
    {
        try
        {
            Guid keyid = (string.IsNullOrEmpty(context.Request["keyid"])) ? Guid.Empty : new Guid(context.Request["keyid"]);
            if (keyid == Guid.Empty)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，钥匙标识丢失");
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 3 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "InOrOut,ActionDay,UsePersonName";
            string fieldtablelist = "case House_KeyUsedInfo.InOrOut when '0' then '归还' when '10' then '借出' end as InOrOut,ActionDay,UsePersonName";
            string orderfield = "House_KeyUsedInfo.AddTime desc";
            string strwhere = string.Format("(KeyReceiptionId='{0}')", keyid);

            System.Data.DataSet ds = null;
            ds = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetList(iPageIndex, iPageSize, orderfield, "House_KeyUsedInfo", strwhere, fieldlist, fieldtablelist, true);
            int count = (int)ds.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetListHtml(ds, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }
            ds.Dispose();
            ds = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }
    
    /// <summary>
    /// 生成列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<div class=\"infos\" title=\"{0}\"> <span class=\"rb\">{0}</span><span class=\"rbpsn\">{1}</span><span class=\"rbtim\">{2:yyyy-MM-dd HH:mm}</span> </div>",
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "InOrOut", ""),
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UsePersonName", ""),
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ActionDay", ""));
        }
        strHtml = sb.ToString();
        return true;
    }
}